package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.attr.BatchAttrUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.base.staticdata.ServiceOfferConst;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;



/**
 * 互联网专线产品开通方式
 * 产品变更,录入界面开通方式置空,其它沿用专线类产品处理逻辑
 */
@Service
public class InternetOpenWayHandler extends AbstractAttrHandler {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String opreatorProvinceNbr= ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        KiteOfferInst mainOfferInst =  querySceneInstService.getMainOfferInst(sceneInstId);
        String specId = Optional.ofNullable(mainOfferInst).map(m -> m.getSpecId()).orElse(null);
        String cataId= null;
        if(!Objects.isNull(specId)){
            cataId= OfferCache.get(specId).getCateId();
        }
        String serviceOfferId = this.querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
        String bizType = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        //核查追单隐藏
        if( KiteStringUtils.equals("ORD10005", commonAttr.getFieldName())&&KiteStringUtils.equalsAny(cataId, ProdCateUtil.getDoubleLineCateIdForArr())&&  KiteStringUtils.equals("1014", serviceOfferId)&&KiteStringUtils.equals("1012", bizType)){
            commonAttr.setShowType("E");
            //commonAttr.getAttrValues().removeIf(p -> KiteStringUtils.equalsAny( p.getAttrValue(),"1","2"));

            // 再把修改的状态写入缓存实例中
            KiteAttr attr = querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
            if (Objects.isNull(attr)) {
                return;
            }
            attr.setShowType("E");
            operateSceneInstService.setCommonAttr(sceneInstId, attr);
        }
        if(KiteStringUtils.isNotEmpty(opreatorProvinceNbr) && KiteStringUtils.equals(opreatorProvinceNbr,"18")
           && KiteStringUtils.isNotEmpty(cataId) && KiteStringUtils.equals(cataId, ProdCateUtil.getSingleCateId(ProdCateUtil.DIA_CODE))){
                commonAttr.setDefaultValue("0");
                commonAttr.setIsEdit("F");
                commonAttr.setValue("0");
                commonAttr.setValueDesc("无需核查直开");
                //commonAttr.getAttrValues().removeIf(p -> KiteStringUtils.equalsAny( p.getAttrValue(),"1","2"));

                // 再把修改的状态写入缓存实例中
                KiteAttr attr = querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
                if (Objects.isNull(attr)) {
                    return;
                }
                attr.setIsEdit("F");
                operateSceneInstService.setCommonAttr(sceneInstId, attr);
        }else {
            String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
            // TODO: 临时处理，二次业务第一次加载清空
            String OpenWayInitLoading = querySceneInstService.getExtParameterValue(sceneInstId, "OpenWayInitLoading");
            if(ServiceOfferConst.service_offer_2826.equals(sceneInst.getServiceOfferId()) && KiteStringUtils.isEmpty(nodeCode) && KiteStringUtils.isEmpty(OpenWayInitLoading)) {
                commonAttr.setValue(null);
                commonAttr.setValueDesc(null);
                setCommonAttr(commonAttr);
                operateSceneInstService.putExtParameter(sceneInstId, "OpenWayInitLoading", "T");
            }
        }
        // 开通方式-补录资料，仅在订单性质=补录单时展示
        String orderNature = querySceneInstService.getCommonAttrValue(sceneInstId, LocalKeyConsts.ORDER_NATURE);
        if(!KiteStringUtils.isEqual(orderNature, "2")) {
            commonAttr.getAttrValues().removeIf(attr -> KiteStringUtils.equals(attr.getAttrValue(), "4"));
            KiteAttr openModeAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.OPEN_WAY);
            openModeAttr.getAttrValues().removeIf(attr -> KiteStringUtils.equals(attr.getAttrValue(), "4"));
            operateSceneCommonService.setCommonAttr(sceneInstId, openModeAttr);
        }

        //河南订购、变更默认为”无需核查直开“
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        String postProvinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(StringUtils.isEmpty(nodeCode)&&KiteStringUtils.equals(LocalKeyConsts.PROVINCE_HENAN,postProvinceNbr) && KiteStringUtils.equalsAny(serviceOfferId,"1","2826")){
            commonAttr.setValue("0");
            commonAttr.setDefaultValue("0");
            commonAttr.setValueDesc("无需核查直开");
            setCommonAttr(commonAttr);
        }
        // 五大双线，业务开通，订单性质、开通方式，签订、重提、追单，不可修改
        // 签订不可编辑
        if(KiteStringUtils.isEqual(nodeCode,"OrderSigned")
            || KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW, LocalServiceOfferConsts.SERVICE_OFFER_TRANSFER_TO_ORDER)
            || (KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER) && KiteStringUtils.isNotEmpty(nodeCode))){
            commonAttr.setIsEdit("F");
            setCommonAttr(commonAttr);
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
            if (Objects.isNull(kiteAttr)) {
                return;
            }
            kiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
            operateSceneInstService.setCommonAttr(sceneInstId, kiteAttr);
        }

        String initFlag = querySceneInstService.getExtParameterValue(sceneInstId, "openWayInited");
        // 河北五大专线产品全场景（业务订购、签订、重提、追单、业务变更）范围内，开通方式隐藏需核查直开、先核查后开通的枚举值
        if(KiteStringUtils.equals(LocalKeyConsts.PROVINCE_HEBEI,postProvinceNbr) && KiteStringUtils.equalsAny(cataId, "2004058","2004029")){
            List<StaticAttrDO> attrValues = commonAttr.getAttrValues();
            attrValues.removeIf(attrValue -> KiteStringUtils.equalsAny(attrValue.getAttrValue(), "1", "2"));

            // 订购和变更场景
            if(KiteStringUtils.equalsAny(serviceOfferId,"1","2826") && KiteStringUtils.isEmpty(nodeCode) && !LocalKeyConsts.IFTRUE_T.equals(initFlag)){
                commonAttr.setDefaultValue("0");
                commonAttr.setValue("0");
                commonAttr.setValueDesc("无需核查直开");
            }
        }
        BatchAttrUtil.batchOpenWayHandle(sceneInstId, serviceOfferId, commonAttr);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        // 无需核查原因
        KiteAttr reasonAttr = querySceneInstService
            .getCommonAttrsByFieldName(sceneInstId, "ORD10015", "93");
        if (Objects.isNull(reasonAttr)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        // 当开通方式选择“无需核查直开”的时候显示 无需核查原因
        if (KiteStringUtils.equals("0", value)) {
            reasonAttr.setShowType("D");
            operateSceneCommonService.setCommonAttr(sceneInstId, reasonAttr);
        } else {
            reasonAttr.setShowType("H");
            operateSceneCommonService.setCommonAttr(sceneInstId, reasonAttr);
        }
        //        跨域优化
        // 以太网、SDH国际6个产品不根据跨域设置  核查方式
//        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
//        String cateId = CuccPosServiceUtils.getCateId(sceneInstId, kiteSceneInst.getCustId());
//        if(!KiteStringUtils.equalsAny(cateId, "2101140","2101142","2101141","2101121","2101122","2101123")) {
//            KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId()).stream()
//                .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
//                .findFirst().orElse(null);
//            String mainServiceOfferId = querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
//            KiteAttr checkWayAttr = SpringUtil.getBean(IQuerySceneCommonService.class).getCommonAttr(sceneInstId, "ORD10222").getResultObject();
//
//            if (null == checkWayAttr) {
//                return super.apply(sceneInstId, fieldName, value, valueDesc);
//            }
//            boolean isCrossDomain = LocalAttrUtils.isCrossDomain(kiteSceneInst, prodInst);
//            LocalAttrUtils.ORD10222(isCrossDomain, mainServiceOfferId, checkWayAttr, value, prodInst.getProdId());
//            operateSceneCommonService.setCommonAttr(sceneInstId, checkWayAttr);
//        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
